//
//  AccountViewModel.swift
//  NSinaWeibo
//
//  Created by LoliQueen on 16/2/18.
//  Copyright © 2016年 LoliQueen. All rights reserved.
//

import UIKit
import AFNetworking

class AccountViewModel: NSObject {
    
    //创建单例
    static let shareAccountViewModel: AccountViewModel = AccountViewModel()
    
    //当前用户模型属性
    var UserAccount : userAccount?
    
    override init(){
        super.init()
        //从沙盒获取的用户信息 处置=给属性
        UserAccount = userAccount.loadUserAccountInfo()
    }
    
    //用户是否登陆成功属性
    var userLogin : Bool {
        return UserAccount?.access_token != nil
    }
    
    //    计算当前登录用户的token
    var access_token: String? {
        return UserAccount?.access_token
    }
    
    //用户名称
    var userName:String?  {
        return UserAccount?.name
    }
    
    //用户头像地址
    var userImageUrl: NSURL?{
        if let urlString = UserAccount?.avatar_large {
            return NSURL(string: urlString)
        }
        return nil
    }
    
    
    
    
    //根据code 换取token令牌
    func loadAccessToken(code:String,finished: (isSucess: Bool)->()){
        //获取AFN管理对象
        //基地址https://api.weibo.com/
        let requestUrlString = "oauth2/access_token"
        let parameters = ["client_id":appKey,"client_secret":appSecret,"grant_type":"authorization_code","code":code,"redirect_uri":redirectUrl]
        let AFN = AFHTTPSessionManager()
        //插入反序列化格式，text/plain
    AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        HTTPClient.sharedClient.requestJSONDict(.POST, urlString: requestUrlString, parameters: parameters) { (dict, error) -> () in
            if error != nil{
                finished(isSucess: false)
                return
            }
            //程序走到这里 就一定转换为了字典类型数据
            let UserAccount = userAccount(dict: dict!)
            print(UserAccount)
            
            //获取用户信息 发起网络请求
            self.loadUserInfo(UserAccount, finished: finished)
        }
      
    }
    
    //获取用户信息，发起网络请求
    private func loadUserInfo(UserAccount:userAccount,finished: (isSucess: Bool)->() ){
        //请求微博首页地址
        //省去基地址
        let urlString = "2/users/show.json"
        //请求参数
        let parameters = ["access_token":UserAccount.access_token!,"uid":UserAccount.uid!]
        //        let AFN = AFHTTPSessionManager()
        
        HTTPClient.sharedClient.requestJSONDict(.GET, urlString: urlString, parameters: parameters) { (dict, error) -> () in
            if error != nil{
                finished(isSucess: false)
                return
            }
            let name = dict!["name"] as! String
            let avatar_large = dict!["avatar_large"] as! String
            //完善模型数据
            UserAccount.name = name
            UserAccount.avatar_large = avatar_large
            //            print(userAccount)
            
            //使用完整的对象 调用归档的方法
            UserAccount.savaUserInfo()
            //用户信息保存完毕之后 执行成功的回调
            
            //需要给单例对象的 用户模型 赋值
            self.UserAccount = UserAccount
            
            finished(isSucess: true)
            print("come here viewmodel")
        }
       
    }
}
